package com.daikit.daikit4gxt.client.action;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoadResultBean;


/**
 * {@link DkAsyncCallbackWrapper} specific for {@link PagingLoadResult}. Override wrapData(Object) to have a more
 * specific wrapping than the default which is cast from RETRIEVED_DATA_TYPE to EXPECTED_DATA_TYPE.
 *
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 * @param <EXPECTED_DATA_TYPE>
 *           the data type for the expected {@link PagingLoadResult}
 * @param <RETRIEVED_DATA_TYPE>
 *           the data type for the retrieved {@link PagingLoadResult}
 */
public class DkAsyncCallbackPagingLoadResultWrapper<EXPECTED_DATA_TYPE, RETRIEVED_DATA_TYPE> extends
		DkAsyncCallbackWrapper<PagingLoadResult<EXPECTED_DATA_TYPE>, PagingLoadResult<RETRIEVED_DATA_TYPE>>
{

	/**
	 * Constructor
	 *
	 * @param callback
	 */
	public DkAsyncCallbackPagingLoadResultWrapper(final AsyncCallback<PagingLoadResult<EXPECTED_DATA_TYPE>> callback)
	{
		super(callback);
	}

	@Override
	protected PagingLoadResult<EXPECTED_DATA_TYPE> wrapResult(final PagingLoadResult<RETRIEVED_DATA_TYPE> result)
	{
		final PagingLoadResultBean<EXPECTED_DATA_TYPE> expectedResult = new PagingLoadResultBean<EXPECTED_DATA_TYPE>();
		expectedResult.setOffset(result.getOffset());
		expectedResult.setTotalLength(result.getTotalLength());
		final List<EXPECTED_DATA_TYPE> expectedList = new ArrayList<EXPECTED_DATA_TYPE>();
		for (final RETRIEVED_DATA_TYPE retrievedData : result.getData())
		{
			expectedList.add(wrapData(retrievedData));
		}
		expectedResult.setData(expectedList);
		return expectedResult;
	}

	/**
	 * Override this method to provide more specific wrapping than default simple cast
	 *
	 * @param retrievedData
	 *           the retrieved data
	 * @return the expected data wrapped from the retrieved data
	 */
	@SuppressWarnings("unchecked")
	protected EXPECTED_DATA_TYPE wrapData(final RETRIEVED_DATA_TYPE retrievedData)
	{
		return (EXPECTED_DATA_TYPE) retrievedData;
	}

}
